package com.lam.system.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.write.handler.WriteHandler;
import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.DictCacheUtils;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.components.easyexcel.export.DownloadUtil;
import com.lam.common.components.easyexcel.imp.ImportUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.system.entity.SysLanguage;
import com.lam.system.entity.imp.SysLanguageImp;
import com.lam.system.listener.UploadSysLanguageListener;
import com.lam.system.param.SysLanguageParam;
import com.lam.system.service.SysLanguageService;

/**
 * 国际化管理Controller
 * 
 * @author admin
 * @date 2022-08-31
 */
@Log(title = "国际化管理")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/sys/language")
public class SysLanguageController extends BaseController {

    @Autowired
    private SysLanguageService sysLanguageService;

    /**
     * 查询国际化管理列表
     */
    @Log(oper="分页查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:list')")
    @GetMapping("/list")
    public Result list(SysLanguageParam param) {
    
        startPage();
        orderByColumn("create_time", "desc");
        List<SysLanguage> list = sysLanguageService.selectList(param);
        return Result.ok(getTableData(list));
    }
    
    /**
     * 导出国际化管理列表
     */
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:export')")
    @Log(businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public Result export(SysLanguageParam param) {
    
    	orderByColumn("create_time", "desc");
        List<SysLanguage> list = sysLanguageService.selectList(param);
        return Result.ok(DownloadUtil.exportExcel("国际化管理导出", list, SysLanguage.class));
    }
    
    @Log(businessType = BusinessType.EXPORT, oper = "下载导入模板")
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:import')")
    @GetMapping("/downloadTemplate")
    public Result downloadTemplate() {
        WriteHandler headRowCommentWriteHandler = ImportUtil.getHeadRowCommentWriteHandler(SysLanguageImp.class, SysLanguage.class, Add.class);
        WriteHandler dropDownWriteHandler = ImportUtil.getDropDownWriteHandler(SysLanguageImp.class, Add.class);
        return Result.ok(DownloadUtil.exportExcel("国际化管理导入模板", Collections.emptyList(), SysLanguageImp.class, 
            headRowCommentWriteHandler, dropDownWriteHandler));
    }
    
    @Log(businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:import')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file, boolean updateSupport) {
        
        logger.info("国际化管理数据导入, 开始接收文件数据...");
        UploadSysLanguageListener readListener = new UploadSysLanguageListener(sysLanguageService);
        readListener.setUpdateSupport(updateSupport);
        ImportUtil.importData("国际化管理", file, readListener);
        Map<String, Object> data = readListener.getOperResult();
        data.put("originalFilename", file.getOriginalFilename());
        return Result.ok(data);
    }
    
    /**
     * 获取国际化管理详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
    	SysLanguage sysLanguage = sysLanguageService.selectById(id);
		if (sysLanguage == null) {
			return Result.fail("errorTip.notExistRecord");
		}
		
		SysLanguageParam param = JsonUtil.toJavaObject(sysLanguage, SysLanguageParam.class, "category", "langKey", "type");
		List<SysLanguage> list = sysLanguageService.selectList(param);
		sysLanguage.setValue(JsonUtil.toJsonString(CollectionUtil.java2Map(list, "lang", "value")));
		
		return Result.ok(sysLanguage);
    }
    
    /**
     * 新增国际化管理
     */
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody SysLanguage sysLanguage) {
    
        return toAjax(sysLanguageService.insert(sysLanguage));
    }
    
    /**
     * 修改国际化管理
     */
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody SysLanguage sysLanguage) {
    
        return toAjax(sysLanguageService.update(sysLanguage));
    }
    
    /**
     * 删除国际化管理
     */
    @PreAuthorize("@ss.hasPm('sys:sysLanguage:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(sysLanguageService.deleteById(id));
    }
    
	@Log(oper="获取国际化语言")
	@GetMapping("/i18nLocale")
	public Result getI18nLocale() {
		return Result.ok(DictCacheUtils.getDictCache("sysLanguage"));
	}
	
	@Log(oper="获取国际化标签")
	@GetMapping("/i18n")
	public Result getI18n(SysLanguageParam param) {
		
		ValidateUtil.validRequired(param.getLang(), "lang不能为空！");
		ValidateUtil.validRequired(param.getCategory(), "category不能为空！");
		
		List<SysLanguage> list = sysLanguageService.selectList(param);
		if(CollectionUtils.isEmpty(list)) {
			return Result.ok(Collections.emptyMap());
		}
		
		Map<String, Map<String, String>> i18nMap = new HashMap<>();
		for (SysLanguage language : list) {
			Map<String, String> typeMap = i18nMap.get(language.getType());
			if(typeMap == null) {
				i18nMap.put(language.getType(), typeMap = new HashMap<>());
			}
			typeMap.put(language.getLangKey(), language.getValue());
		}
		return Result.ok(i18nMap);
	}

}
